package com.example.myjavafx.controller;

import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.Alert;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.input.MouseEvent;
import javafx.scene.layout.StackPane;
import javafx.scene.shape.Rectangle;
import javafx.stage.FileChooser;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.util.ResourceBundle;

public class CropController implements Initializable {
    @FXML
    private StackPane imageContainer;
    @FXML private ImageView preview;
    @FXML private Rectangle cropRect;

    private File selectedFile;
    private double startX, startY;
    private double scaleX = 1.0;
    private double scaleY = 1.0;

    @Override
    public void initialize(URL location, ResourceBundle resources) {
        setupCropRectangle();
        setupImageScalingListener();
    }

    private void setupCropRectangle() {
        cropRect.setManaged(false);
        cropRect.widthProperty().addListener((obs, oldVal, newVal) -> {
            if (newVal.doubleValue() < 0) cropRect.setWidth(0);
        });
        cropRect.heightProperty().addListener((obs, oldVal, newVal) -> {
            if (newVal.doubleValue() < 0) cropRect.setHeight(0);
        });
    }

    private void setupImageScalingListener() {
        preview.boundsInParentProperty().addListener((obs, oldVal, newVal) -> {
            if (preview.getImage() != null) {
                scaleX = preview.getImage().getWidth() / newVal.getWidth();
                scaleY = preview.getImage().getHeight() / newVal.getHeight();
            }
        });
    }

    @FXML
    private void handleUpload(ActionEvent event) {
        FileChooser fileChooser = new FileChooser();
        fileChooser.setTitle("选择图片文件");
        fileChooser.getExtensionFilters().addAll(
                new FileChooser.ExtensionFilter("图片文件", "*.png", "*.jpg", "*.jpeg")
        );

        selectedFile = fileChooser.showOpenDialog(imageContainer.getScene().getWindow());
        if (selectedFile != null) {
            loadImage(selectedFile);
            cropRect.setVisible(false);
        }
    }

    private void loadImage(File file) {
        Image image = new Image(file.toURI().toString());
        preview.setImage(image);

        // 保持图片比例
        if (image.getWidth() > image.getHeight()) {
            preview.setFitWidth(600);
        } else {
            preview.setFitHeight(400);
        }
    }

    @FXML
    private void handleMousePressed(MouseEvent event) {
        if (preview.getImage() == null) return;

        startX = event.getX();
        startY = event.getY();

        cropRect.setX(startX);
        cropRect.setY(startY);
        cropRect.setWidth(0);
        cropRect.setHeight(0);
        cropRect.setVisible(true);
    }

    @FXML
    private void handleMouseDragged(MouseEvent event) {
        if (!cropRect.isVisible()) {
            return;
        }

        double currentX = event.getX();
        double currentY = event.getY();

        cropRect.setX(Math.min(startX, currentX));
        cropRect.setY(Math.min(startY, currentY));
        cropRect.setWidth(Math.abs(currentX - startX));
        cropRect.setHeight(Math.abs(currentY - startY));
    }

    @FXML
    private void handleCrop(ActionEvent event) {
        if (selectedFile == null || !cropRect.isVisible()) {
            return;
        }

        try {
            int x = (int)(cropRect.getX() * scaleX);
            int y = (int)(cropRect.getY() * scaleY);
            int width = (int)(cropRect.getWidth() * scaleX);
            int height = (int)(cropRect.getHeight() * scaleY);

            // 发送到后端（保持之前的实现）
            sendToBackend(selectedFile, x, y, width, height);
        } catch (Exception e) {
            showAlert("错误", "裁剪操作失败: " + e.getMessage());
        }
    }

    // 保持原有的sendToBackend和showAlert方法
    // ...
    private void sendToBackend(File imageFile, int x, int y, int width, int height) {
        try {
            // 创建多部分请求
            HttpURLConnection connection = (HttpURLConnection) new URL("http://localhost:8080/api/crop").openConnection();
            connection.setRequestMethod("POST");
            connection.setDoOutput(true);

            String boundary = "----WebKitFormBoundary7MA4YWxkTrZu0gW";
            connection.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);

            try (OutputStream output = connection.getOutputStream();
                 PrintWriter writer = new PrintWriter(new OutputStreamWriter(output, StandardCharsets.UTF_8), true)) {

                // 添加文件部分
                writer.append("--" + boundary).append("\r\n");
                writer.append("Content-Disposition: form-data; name=\"file\"; filename=\"" + imageFile.getName() + "\"").append("\r\n");
                writer.append("Content-Type: image/" + getFileExtension(imageFile)).append("\r\n\r\n");
                writer.flush();

                Files.copy(imageFile.toPath(), output);
                output.flush();

                // 添加裁剪参数
                writer.append("\r\n--" + boundary).append("\r\n");
                writer.append("Content-Disposition: form-data; name=\"cropData\"").append("\r\n\r\n");
                writer.append(String.format("x=%d&y=%d&width=%d&height=%d", x, y, width, height));

                writer.append("\r\n--" + boundary + "--").append("\r\n");
            }

            // 处理响应
            int responseCode = connection.getResponseCode();
            if (responseCode == 200) {
                try (InputStream input = connection.getInputStream()) {
                    Files.copy(input, Paths.get("cropped_result.png"), StandardCopyOption.REPLACE_EXISTING);
                    showAlert("成功", "图片已保存为 cropped_result.png");
                }
            } else {
                showAlert("错误", "服务器返回错误: " + responseCode);
            }
        } catch (Exception e) {
            showAlert("错误", "网络请求失败: " + e.getMessage());
        }
    }
    private void showAlert(String title, String content) {
        Alert alert = new Alert(Alert.AlertType.INFORMATION);
        alert.setTitle(title);
        alert.setHeaderText(null);
        alert.setContentText(content);
        alert.showAndWait();
    }
    private String getFileExtension(File file) {
        String name = file.getName();
        int lastIndexOf = name.lastIndexOf(".");
        if (lastIndexOf == -1) {
            return "";
        }
        return name.substring(lastIndexOf + 1);
    }
}
